package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"userprofile/api/internal/types"
	"userprofile/pkg"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation

		token := r.Header.Get("token")

		if token == "" {
			resp := types.Response{
				Message: "未登录",
				Code:    "500",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return

		}
		getToken, errString := pkg.GetToken(token)

		if errString != "" {
			resp := types.Response{
				Message: errString,
				Code:    "500",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		r.ParseForm()
		r.Form.Set("userid", getToken["userid"].(string))
		// Passthrough to next handler if need
		next(w, r)
	}
}
